package com.sinoglobal.shakeprize.activity;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sinoglobal.shakeprize.R;
import com.sinoglobal.shakeprize.activity.prize.MyPrizeActivity;
import com.sinoglobal.shakeprize.bean.RemainNum;
import com.sinoglobal.shakeprize.bean.ResponsePrizeInfo;
import com.sinoglobal.shakeprize.utils.Contstent;
import com.sinoglobal.shakeprize.utils.FlyUtil;
import com.sinoglobal.shakeprize.utils.ItktLog;
import com.sinoglobal.shakeprize.utils.OKhttpUtil;
import com.sinoglobal.shakeprize.utils.OKhttpUtil.ResponseCallback;
import com.sinoglobal.shakeprize.utils.SPUtil;
import com.squareup.picasso.Picasso;

import okhttp3.Request;

/**
 * @author temulu
 * @createdate 2015-8-26下午2:35:34
 * @Description 摇一摇界面
 */
public class ShakeActivity extends FragmentActivity implements OnClickListener {
	private static final int SHAKE_NUMBER = 0;// 摇奖次数
	private static final int SHAKE_END = 1;// 摇动结束
	private static final int SHAKE_FAIL = 2;// json解析失败

	private ImageView shakeImgUp;
	private ImageView shakeImgDown;
	private ImageView shakeImgUpLine;
	private ImageView shakeImgDownLine;
	private TextView shakeTextDescription;
	private TextView shakeTextCount;// 剩余次数
	private RelativeLayout shakeExpose;// 等待奖品揭晓的提示
	private ShakeListener mShakeListener;
	private Vibrator mVibrator;
	private boolean isChanged = true;
	private View toastView;
	private Toast toast;
	private View dialogView;
	private ImageView dialogCancle;
	private ImageView dialogPrize;
	private TextView dialogPrizeDes;
	private TextView dialogOutburst;
	private Button dialogButton;
	private Dialog dialog;
	private int shakeCount;
	private int sessionListSize;
	private int sessionRoundId;
	private ResponsePrizeInfo rsPrize;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		FlyUtil.addAppActivity(this);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.shake_activity_shake);
		sessionRoundId = getIntent().getIntExtra("roundid", 0);
		sessionListSize = getIntent().getIntExtra("size", 0);
		isLoginIntentLoginActivity();
		accessShakeNumber();
		initView();
		disposeAnimation();
	}

	private void initView() {
		ImageView shakeTitleLeft = (ImageView) findViewById(R.id.shakeTitleLeft);
		shakeTitleLeft.setImageResource(R.drawable.home_arrow);
		shakeTitleLeft.setOnClickListener(this);
		ImageView shakeTitleRight = (ImageView) findViewById(R.id.shakeTitleRight);
		shakeTitleRight.setOnClickListener(this);
		shakeImgUp = (ImageView) findViewById(R.id.shakeImgUp);
		shakeImgDown = (ImageView) findViewById(R.id.shakeImgDown);
		shakeImgUpLine = (ImageView) findViewById(R.id.shakeImgUpLine);
		shakeImgDownLine = (ImageView) findViewById(R.id.shakeImgDownLine);
		shakeTextDescription = (TextView) findViewById(R.id.shakeTextdescription);
		shakeTextCount = (TextView) findViewById(R.id.shakeTextCount);
		shakeExpose = (RelativeLayout) findViewById(R.id.shakeExpose);
		shakeTitleRight.setImageResource(R.drawable.home_icon_list);

	}

	@Override
	public void onClick(View v) {
		if (v.getId()==R.id.shakeTitleLeft) {
			goHome();
		} else if(v.getId()==R.id.shakeTitleRight){
			// 进入更多场次界面
						if (sessionListSize > 0) {
							FlyUtil.intentForward(this, ShakeSessionActivity.class);
						} else {
							showToast("当前没有更多场次");
						}
		}else if(v.getId()==R.id.dialogCancle){
			dialog.cancel();
		}else if(v.getId()==R.id.dialogButton){
			if (1004 == rsPrize.rsNo) {
				Intent intent = new Intent(ShakeActivity.this,
						MyPrizeActivity.class);
				startActivity(intent);
			}
			dialog.cancel();
		}
	}

	/** 处理摇一摇动画 */
	private void disposeAnimation() {
		mShakeListener = new ShakeListener(this);
		mShakeListener.setOnShakeListener(new ShakeListener.OnShakeListener() {

			@Override
			public void onShake() {
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
				if (shakeCount > 0) {
					startAnim();
					mShakeListener.stop();
					mVibrator = ((Vibrator) getApplication().getSystemService(
							VIBRATOR_SERVICE));
					mVibrator.vibrate(500);
				} else {
					showToast("");
				}
			}
		});

	}

	/** 摇一摇动画 */
	private void startAnim() {
		AnimationSet animup = new AnimationSet(true);
		TranslateAnimation mytranslateanimup0 = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
				-0.8f);
		mytranslateanimup0.setDuration(300);
		TranslateAnimation mytranslateanimup1 = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
				+0.8f);
		mytranslateanimup1.setDuration(300);
		mytranslateanimup1.setStartOffset(500);
		animup.addAnimation(mytranslateanimup0);
		animup.addAnimation(mytranslateanimup1);
		shakeImgUp.startAnimation(animup);
		shakeImgUpLine.startAnimation(animup);

		AnimationSet animdn = new AnimationSet(true);
		TranslateAnimation mytranslateanimdn0 = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
				+0.8f);
		mytranslateanimdn0.setDuration(300);
		TranslateAnimation mytranslateanimdn1 = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
				-0.8f);
		mytranslateanimdn1.setDuration(300);
		mytranslateanimdn1.setStartOffset(500);
		animdn.addAnimation(mytranslateanimdn0);
		animdn.addAnimation(mytranslateanimdn1);
		shakeImgDown.startAnimation(animdn);
		shakeImgDownLine.startAnimation(animdn);
		animdn.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				shakeImgUpLine.setVisibility(View.VISIBLE);
				shakeImgDownLine.setVisibility(View.VISIBLE);
			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				mVibrator.cancel();
				mShakeListener.start();
				shakeImgUpLine.setVisibility(View.INVISIBLE);
				shakeImgDownLine.setVisibility(View.INVISIBLE);
				shakePrize();
			}

		});
	}

	/** 处理动画执行后的操作 */
	private void dispathOperation() {
		if (shakeCount > 0) {
			shakeCount--;
			shakeTextCount.setText("今日还有" + shakeCount + "次机会");
		}
	}

	/** 变换提示内容 */
	private void shakeTextStateChange() {
		if (isChanged) {
			shakeExpose.setVisibility(View.VISIBLE);
			shakeTextDescription.setVisibility(View.INVISIBLE);
		} else {
			shakeExpose.setVisibility(View.INVISIBLE);
			shakeTextDescription.setVisibility(View.VISIBLE);
		}
		isChanged = !isChanged;
	}

	/** 返回主页 */
	protected void goHome() {
		Intent intent = new Intent();
		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		finish();
	}

	/** 判断是否登录并跳转到登录界面 */
	public boolean isLoginIntentLoginActivity() {
		if (TextUtils.isEmpty(SPUtil.getString(ShakeActivity.this, Contstent.USER_ID))) {
			startActivity(new Intent("com.sinoglobal.ningxia.Login"));
			overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
			return false;
		}
		return true;
	};

	/**
	 * 奖品dialog
	 * 
	 * @param url
	 * @param prizeDes
	 */
	private void showShakeDialog() {
		if (dialogView == null) {
			dialogView = View.inflate(this, R.layout.shake_dialog_layout, null);
			dialogCancle = (ImageView) dialogView
					.findViewById(R.id.dialogCancle);
			dialogPrize = (ImageView) dialogView.findViewById(R.id.dialogPrize);
			dialogOutburst = (TextView) dialogView
					.findViewById(R.id.dialogOutburst);
			dialogPrizeDes = (TextView) dialogView
					.findViewById(R.id.dialogPrizeDes);
			dialogButton = (Button) dialogView.findViewById(R.id.dialogButton);
			dialog = new Dialog(this,R.style.shake_dialog_theme);
			dialog.setContentView(dialogView);
			dialog.getWindow().setBackgroundDrawable(new BitmapDrawable());
			dialogCancle.setOnClickListener(this);
			dialogButton.setOnClickListener(this);
		}
		if (1005 == rsPrize.rsNo) {
			dialogPrize
					.setImageResource(R.drawable.home_pop_ico_expression);
			dialogOutburst.setText(getString(R.string.shake_text_dialog_des));
			dialogPrizeDes.setText(getString(R.string.shake_text_dialog_go_on));
			dialogButton.setText("今日还有" + shakeCount + "次机会");
		} else if (1004 == rsPrize.rsNo) {
			Picasso.with(this).load(Contstent.PICTURE_PATH+rsPrize.rs.prizepic).into(dialogPrize);
			dialogOutburst
					.setText(getString(R.string.shake_text_dialog_outburst));
			dialogButton.setText("马上领取");
			switch (rsPrize.rs.prizetype) {
			case 1:
				dialogPrizeDes.setText("恭喜，获得" + rsPrize.rs.name);
				break;
			case 2:
				dialogPrizeDes.setText("恭喜，获得" + rsPrize.rs.name + "已放入您的账户");
				break;
			}
		}
		dialog.show();
	}

	private void showToast(String str) {
		if (toastView == null) {
			toastView = View.inflate(this, R.layout.shake_toast_layout, null);
			TextView message = (TextView) toastView
					.findViewById(R.id.toastText);
			if (!TextUtils.isEmpty(str)) {
				message.setText(str);
			}
			toast = new Toast(getApplicationContext());
			toast.setGravity(Gravity.FILL, 0, 0);
			toast.setDuration(Toast.LENGTH_SHORT);
			toast.setView(toastView);
		}
		toast.show();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mShakeListener.start();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mShakeListener.stop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mShakeListener.stop();
	}

	/** 摇奖次数 */
	private void accessShakeNumber() {
		Map<String, Object> request = new HashMap<String, Object>();
		request.put("roundid", "" + sessionRoundId);
		request.put("productCode", Contstent.PRODUCT_IDENTIFICATION);
		request.put("userId", SPUtil.getString(ShakeActivity.this, Contstent.USER_ID));
		String json = JSONObject.toJSONString(request);
		String url = Contstent.SHAKE_PATH + "yaoyiyao/userRemainNum.do?json="
				+ json;
		OKhttpUtil.enqueue(url, new ResponseCallback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {

			}

			@Override
			public void onResponse(String json) throws IOException {
				ItktLog.e("Response:"+json);
				try {
					RemainNum remainNum = JSON.parseObject(json, RemainNum.class);
					if (TextUtils.isEmpty(remainNum.rs.remainNum)) {
						shakeCount = 0;
					} else {
						shakeCount = Integer.parseInt(remainNum.rs.remainNum);
					}
					shakeTextCount.setText("今日还有" + shakeCount + "次机会");
				} catch (Exception e) {
					Toast.makeText(ShakeActivity.this, "访问网络失败，请稍后再试", Toast.LENGTH_SHORT).show();
					return;
				}
				
			}
		});
	}

	/** 摇奖 */
	private void shakePrize() {
		shakeTextStateChange();
		Map<String, Object> request = new HashMap<String, Object>();
		request.put("roundid", sessionRoundId);
		request.put("productCode", Contstent.PRODUCT_IDENTIFICATION);
		request.put("userId", SPUtil.getString(ShakeActivity.this, Contstent.USER_ID));
		request.put("permissionCode", Contstent.MODULE_IDENTIFICATION);
		request.put("username", SPUtil.getString(
				ShakeActivity.this, "nickname"));
		String json = JSONObject.toJSONString(request);
		String url = Contstent.SHAKE_PATH + "yaoyiyao/shakeCourse.do?json="
				+ json;
		OKhttpUtil.enqueue(url, new ResponseCallback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {

			}

			@Override
			public void onResponse(String json) throws IOException {
				ItktLog.e("prizeInfo:"+json);
				shakeTextStateChange();
				try {
					rsPrize = JSONObject.parseObject(json,
							ResponsePrizeInfo.class);
				} catch (Exception e) {
					Toast.makeText(ShakeActivity.this, "访问网络失败，请稍后再试", Toast.LENGTH_SHORT).show();
					return;
				}
				dispathOperation();
				showShakeDialog();
			}
		});
	}
}
